package com.wenhui.schoolyardinfo.mine.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.wenhui.schoolyardinfo.R;
import com.wenhui.schoolyardinfo.base.BaseActivity;
import com.wenhui.schoolyardinfo.base.BaseMvpActivity;
import com.wenhui.schoolyardinfo.callback.RcvOnItemViewClickListener;
import com.wenhui.schoolyardinfo.customview.CircleImageView;
import com.wenhui.schoolyardinfo.customview.CommonPopupWindow;
import com.wenhui.schoolyardinfo.login.view.base.IBaseView;
import com.wenhui.schoolyardinfo.manager.DateManager;
import com.wenhui.schoolyardinfo.manager.InputManager;
import com.wenhui.schoolyardinfo.manager.LogManager;
import com.wenhui.schoolyardinfo.mine.adapter.SelectTypeAdapter;
import com.wenhui.schoolyardinfo.mine.bean.PersonalDataBean;
import com.wenhui.schoolyardinfo.mine.bean.SelectTypeBean;
import com.wenhui.schoolyardinfo.mine.presenter.MinePresenterImpl;
import com.wenhui.schoolyardinfo.mine.presenter.base.IMinePresenter;
import com.wenhui.schoolyardinfo.mine.view.IPersonalDataView;
import com.wenhui.schoolyardinfo.release.adapter.SelectPhotosAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author    : Urasaki
 * e-mail    : 1164688204@qq.com
 * date      : 2019/7/5 11:07
 * introduce : 个人资料Activity
 */

public class PersonalDataActivity extends BaseMvpActivity<IBaseView, MinePresenterImpl> implements IPersonalDataView {

    private static final String TAG = "PersonalDataActivity";
    @BindView(R.id.imv_back)
    ImageView imvBack;
    @BindView(R.id.layout_back)
    RelativeLayout layoutBack;
    @BindView(R.id.tev_title)
    TextView tevTitle;
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.tev_head_portrait)
    TextView tevHeadPortrait;
    @BindView(R.id.imv_head_portrait)
    CircleImageView imvHeadPortrait;
    @BindView(R.id.layout_head_portrait)
    RelativeLayout layoutHeadPortrait;
    @BindView(R.id.tev_name_prompting)
    TextView tevNamePrompting;
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.layout_name)
    RelativeLayout layoutName;
    @BindView(R.id.tev_personal_signature_prompting)
    TextView tevPersonalSignaturePrompting;
    @BindView(R.id.layout_personal_signature)
    RelativeLayout layoutPersonalSignature;
    @BindView(R.id.tev_sex_prompting)
    TextView tevSexPrompting;
    @BindView(R.id.tev_sex)
    TextView tevSex;
    @BindView(R.id.layout_sex)
    RelativeLayout layoutSex;
    @BindView(R.id.tev_birthday_prompting)
    TextView tevBirthdayPrompting;
    @BindView(R.id.tev_birthday)
    TextView tevBirthday;
    @BindView(R.id.layout_birthday)
    RelativeLayout layoutBirthday;
    @BindView(R.id.tev_label_prompting)
    TextView tevLabelPrompting;
    @BindView(R.id.edt_label)
    EditText edtLabel;
    @BindView(R.id.layout_label)
    RelativeLayout layoutLabel;
    @BindView(R.id.tev_preserve)
    TextView tevPreserve;
    @BindView(R.id.view_bottom)
    View viewBottom;
    private QMUILoadingView loadView;

    //Popwindow
    private CommonPopupWindow headPortraitWindow;
    //Popwindow
    private CommonPopupWindow window;
    private RecyclerView selectPhotosRecyclerView;
    private RecyclerView selectTypeRecyclerView;
    private SelectPhotosAdapter selectPhotosAdapter;
    private SelectTypeAdapter selectTypeAdapter;
    private List<String> stringheadPortraitList;
    private List<SelectTypeBean> selectTypeBeanList;

    private LinearLayoutManager layoutManager;
    //个人资料
    private PersonalDataBean personalDataBean;

    private Calendar selectedDate;
    private Calendar startDate;
    private Calendar endDate;
    //时间选择器
    private TimePickerView timePickerView;
    private String birthday;
    //头像
    private List<LocalMedia> headPortraitList;

    private Map<String, String> bodyParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        ButterKnife.bind(this);

        initData();
        initViews();
    }

    @Override
    protected void initData() {
        personalDataBean = new PersonalDataBean("http://ww1.sinaimg.cn/large/0065oQSqly1frv032vod8j30k80q6gsz.jpg",
                "埃尔温.隆美尔", "", "爱尔兰", "爱丁堡大学",
                20, "男", 10000000000000L, 100, 101,
                "https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/" +
                        "sign=5b4f6ad1a74bd11310c0bf603bc6cf6a/023b5bb5c9ea15cea5096eabbc003af33b87b2a9.jpg");
        stringheadPortraitList = new ArrayList<>();
        stringheadPortraitList.add(getResources().getString(R.string.selection_from_mobile_phone_album));
        stringheadPortraitList.add(getResources().getString(R.string.shoot));
        stringheadPortraitList.add(getResources().getString(R.string.cancel));
        selectTypeBeanList = new ArrayList<>();
        selectTypeBeanList.add(new SelectTypeBean("男", false));
        selectTypeBeanList.add(new SelectTypeBean("女", false));
        selectTypeBeanList.add(new SelectTypeBean("取消", false));
        headPortraitList = new ArrayList<>();

        startDate = Calendar.getInstance();
        endDate = Calendar.getInstance();
        selectedDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(1919, 0, 1);


        loadView = new QMUILoadingView(this);
        loadView.setVisibility(View.GONE);
        loadView.setSize(120);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        addContentView(loadView, layoutParams);


        bodyParams = new HashMap<>();
        bodyParams.put("", "");
        bodyParams.put("", "");
        presenter = initPresenter();
//        presenter.getPersonalData(bodyParams);
    }

    @Override
    protected void initViews() {
        setTopBar(topbar);

        Glide.with(this).load(personalDataBean.getHeadPortraitUrl()).into(imvHeadPortrait);
        if (personalDataBean.getName() != null && !"".equals(personalDataBean.getName())) {
            edtName.setText(personalDataBean.getName());
        }
        tevSex.setText(personalDataBean.getSex());
        tevBirthday.setText(DateManager.millisecondConvertedToDate(personalDataBean.getBirthday()));
        if (personalDataBean.getLabel() != null && !"".equals(personalDataBean.getLabel())) {
            edtLabel.setText(personalDataBean.getLabel());
        } else {
            edtLabel.setHint(getResources().getString(R.string.please_enter_the_label));
        }

        initPopupWindow();
        initTimePicker();
    }

    @Override
    protected MinePresenterImpl initPresenter() {
        return new MinePresenterImpl(this, this);
    }

    private void initPopupWindow() {
        // create popup window
        headPortraitWindow = new CommonPopupWindow(PersonalDataActivity.this, R.layout.popup_window_release, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initViews() {
                View view = getContentView();
                selectPhotosRecyclerView = view.findViewById(R.id.select_photos_recycler_view);
                layoutManager = new LinearLayoutManager(PersonalDataActivity.this);
                layoutManager.setOrientation(OrientationHelper.VERTICAL);
                selectPhotosRecyclerView.setLayoutManager(layoutManager);
                selectPhotosRecyclerView.setItemAnimator(new DefaultItemAnimator());

                selectPhotosAdapter = new SelectPhotosAdapter(PersonalDataActivity.this);
                selectPhotosRecyclerView.setAdapter(selectPhotosAdapter);
                selectPhotosAdapter.clearData();
                selectPhotosAdapter.addAllData(stringheadPortraitList);
            }

            @Override
            protected void initEvent() {
                selectPhotosAdapter.setRcvOnItemViewClickListener(new RcvOnItemViewClickListener() {
                    @Override
                    public void onItemClickListener(int position, View view) {
                        switch (position) {
                            case 0:
                                showToast("selection_from_mobile_phone_album");
                                // 进入相册 以下是例子：不需要的api可以不写
                                PictureSelector.create(PersonalDataActivity.this)
                                        .openGallery(PictureMimeType.ofAll())
//                                        .theme(themeId)
                                        .maxSelectNum(1)
                                        .minSelectNum(0)
                                        .selectionMode(PictureConfig.MULTIPLE)
                                        .previewImage(true)
                                        .previewVideo(true)
                                        .enablePreviewAudio(true) // 是否可播放音频
                                        .isCamera(false)
                                        .enableCrop(false)
                                        .compress(true)
                                        .isGif(false)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                break;
                            case 1:
                                showToast("shoot");
                                //拍照
                                PictureSelector.create(PersonalDataActivity.this)
                                        .openCamera(PictureMimeType.ofImage())
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                break;
                            case 2:
                                showToast("cancel");
                                break;
                            default:
                                break;
                        }
                        headPortraitWindow.getPopupWindow().dismiss();
                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance = getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 1.0f;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getWindow().setAttributes(lp);
                    }
                });
            }
        };

        // create popup window
        window = new CommonPopupWindow(PersonalDataActivity.this, R.layout.popup_window_release, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initViews() {
                View view = getContentView();
                layoutManager = new LinearLayoutManager(PersonalDataActivity.this);
                layoutManager.setOrientation(OrientationHelper.VERTICAL);

                selectTypeRecyclerView = view.findViewById(R.id.select_photos_recycler_view);
                selectTypeRecyclerView.setItemAnimator(new DefaultItemAnimator());
                selectTypeRecyclerView.setLayoutManager(layoutManager);

                selectTypeAdapter = new SelectTypeAdapter(PersonalDataActivity.this);
                selectTypeRecyclerView.setAdapter(selectTypeAdapter);
                selectTypeAdapter.clearData();
                selectTypeAdapter.addAllData(selectTypeBeanList);
            }

            @Override
            protected void initEvent() {
                selectTypeAdapter.setRcvOnItemViewClickListener(new RcvOnItemViewClickListener() {
                    @Override
                    public void onItemClickListener(int position, View view) {
                        switch (position) {
                            case 0:
                                showToast("selection_sex_0");
                                selectTypeBeanList.set(0, new SelectTypeBean("男", true));
                                selectTypeBeanList.set(1, new SelectTypeBean("女", false));
                                tevSex.setText(selectTypeBeanList.get(position).getType());
                                break;
                            case 1:
                                showToast("selection_sex_1");
                                selectTypeBeanList.set(0, new SelectTypeBean("男", false));
                                selectTypeBeanList.set(1, new SelectTypeBean("女", true));
                                tevSex.setText(selectTypeBeanList.get(position).getType());
                                break;
                            case 3:
                                showToast("cancel");
                                break;
                            default:
                                break;
                        }
                        window.getPopupWindow().dismiss();
                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance = getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 1.0f;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getWindow().setAttributes(lp);
                    }
                });
            }
        };
    }

    private void showHeadPortraitPopupWindow(View anchorView) {
        PopupWindow mPopupWindow = headPortraitWindow.getPopupWindow();
        mPopupWindow.setAnimationStyle(R.style.PopupWindowTranslucentTheme);
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_corners_2_blue_a));
        // 设置点击窗口外边窗口消失
        mPopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        mPopupWindow.setFocusable(true);

        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 10);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    private void showPopupWindow(View anchorView) {
        selectTypeAdapter.clearData();
        selectTypeAdapter.addAllData(selectTypeBeanList);
        //        View contentView = CommonPopupWindow();
//        mPopupWindow = new PopupWindow(contentView,
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
//        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
//        // 设置好参数之后再show
//        int windowPos[] = PopupWindowManager.calculatePopWindowPos(anchorView, contentView);
//        int xOff = 20; // 可以自己调整偏移
//        windowPos[0] -= xOff;
//        mPopupWindow.showAtLocation(anchorView, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);

        PopupWindow mPopupWindow = window.getPopupWindow();
        mPopupWindow.setAnimationStyle(R.style.animTranslate);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        // 设置点击窗口外边窗口消失
        mPopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        mPopupWindow.setFocusable(true);
//        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    private void initTimePicker() {
        timePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                birthday = DateManager.getTime(date);
                tevBirthday.setText(birthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
//                .setTitleSize(20)//标题文字大小
//                .setTitleText("时间选择")//标题文字
                .setCancelText(getResources().getString(R.string.cancel))//取消按钮文字
                .setSubmitText(getResources().getString(R.string.determine))//确定按钮文字
                .setContentTextSize(16)//设置滚轮文字大小
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.colorBlueA))//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.colorWhiteA))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.colorWhiteA))//滚轮背景颜色 Night mode
                .setLineSpacingMultiplier(2.4f)//设置子项之间的间距
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
    }

    @Override
    public void showLoading() {
        loadView.setVisibility(View.VISIBLE);
        loadView.start();
    }

    @Override
    public void hideLoading() {
        loadView.stop();
        loadView.setVisibility(View.GONE);
    }

    @Override
    public void getPersonalDataSuccess(String success) {

    }

    @Override
    public void getPersonalDataError(String error) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogManager.i(TAG, "onActivityResult");
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    headPortraitList = PictureSelector.obtainMultipleResult(data);
                    LogManager.i(TAG, headPortraitList.get(0).getPath());
                    Glide.with(this).load(headPortraitList.get(0).getCompressPath()).into(imvHeadPortrait);
                    break;
                default:
                    break;
            }
        }
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
    }

    @OnClick({R.id.layout_back, R.id.layout_head_portrait, R.id.layout_name, R.id.layout_personal_signature, R.id.layout_sex, R.id.layout_birthday, R.id.layout_label, R.id.tev_preserve})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_head_portrait:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtLabel.setFocusable(false);
                InputManager.hideInput(edtLabel);
                showHeadPortraitPopupWindow(viewBottom);
                break;
            case R.id.layout_name:
                edtName.setSelection(personalDataBean.getName().length());
                edtName.setFocusable(true);
                edtName.setFocusableInTouchMode(true);
                edtName.requestFocus();
                InputManager.showInput(edtName);
                break;
            case R.id.layout_personal_signature:
                startActivity(PersonalSignatureActivity.class);
                break;
            case R.id.layout_sex:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtLabel.setFocusable(false);
                InputManager.hideInput(edtLabel);
                showPopupWindow(viewBottom);
                break;
            case R.id.layout_birthday:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtLabel.setFocusable(false);
                InputManager.hideInput(edtLabel);
                timePickerView.show(view);//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
                break;
            case R.id.layout_label:
                edtLabel.setSelection(personalDataBean.getLabel().length());
                edtName.setFocusable(false);
                edtLabel.setFocusable(true);
                edtLabel.setFocusableInTouchMode(true);
                edtLabel.requestFocus();
                InputManager.showInput(edtLabel);
                break;
            case R.id.tev_preserve:
                edtName.setFocusable(false);
                InputManager.hideInput(edtName);
                edtLabel.setFocusable(false);
                InputManager.hideInput(edtLabel);
                showToast("tev_preserve");
                break;
        }
    }
}
